package com.yc.web.servlets;

import com.yc.web.model.JsonModel;
import com.yc.bean.ShoeStatus;
import com.yc.bean.Shoes;
import com.yc.bean.User;
import com.yc.web.model.CartItem;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.yc.utils.YcConstants.USER;

@WebServlet(name = "OrderServlet",value = "/order.action")
public class OrderServlet extends BaseServlet{
    //加入购物车
    protected void order(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        int sid = Integer.parseInt(req.getParameter("sid"));
        int num = Integer.parseInt(req.getParameter("num"));
        HttpSession session = req.getSession();//取出session会话对象
        JsonModel jm = new JsonModel();

        Map<Integer, CartItem> cart = new HashMap<Integer,CartItem>();//购物车  集合
        //判断是否登录
//        if (session.getAttribute(LOGINUSER)==null){
//            jm.setCode(-1);
//            super.writeJson(jm,resp);
//            return;
//        }
        //判断原本购物车中是否有商品
        if (session.getAttribute("cart")!=null){
            cart = (Map<Integer, CartItem>) session.getAttribute("cart");
        }
        CartItem ci=null;
        if (cart.containsKey(sid)){
            //判断  用户是否购买了这个商品
            //如果有  则数量++
            ci = cart.get(sid);
            ci.setNum(ci.getNum()+num);

        }else {
            //查询出这个商品对象，   构建一个CartItem对象
            //1.根据id查找这本书
            String sql ="SELECT Shoes.sid,sbrand,sgender,ssize,scolor,style,sprice,sdescription,sstockquantity,photourl,ismain\n" +
                    "FROM Shoes JOIN ShoePhotos ON Shoes.sid = ShoePhotos.sid JOIN ShoeStyle ON Shoes.sstyle=ShoeStyle.styleid\n" +
                    "WHERE Shoes.sid=? and ismain='true'";
            List<Shoes> fList =  db.select(Shoes.class,sql,sid+"");
            //从Tomcat中session中取商品
//            List<Resfood> fList = (List<Resfood>) session.getAttribute("foodList");
            Shoes b = null;
            if (fList!=null && fList.size()>0){
                b=fList.get(0);
            }
            //2.创建购物条目，设置数量
            ci = new CartItem();
            ci.setShoes(b);
            ci.setNum(num);
        }
        //判断购物条目的数量是否小于等于0  如果是  则从cart中remove这个商品
        //                                不是   则将购物条目添加到Cart中去
        if (ci.getNum()<=0){
            cart.remove(sid);
        }else {
            ci.getSmallCount(); //强制计算小计
            //3.将购物条目放到 Map<Integer，CartItem> cart购物车
            cart.put(sid,ci);
        }
        //4.存入session
        session.setAttribute("cart",cart);
        //5.返回jsonModel(code=1，obj=cart.values(所有的CartItem集合))

        jm.setCode(1);
        //cart是一个map   我们取这个map的值   Set[CartItem,CartItem,CartItem]
        jm.setObj(cart.values());

        super.writeJson(jm,resp);
    }

    //保持购物车状态
    protected void getCartFoods(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        HttpSession session = req.getSession();//取出session会话对象
        Map<Integer, CartItem> cart = new HashMap<Integer,CartItem>();//购物车  集合
        if (session.getAttribute("cart")!=null){
            cart = (Map<Integer, CartItem>) session.getAttribute("cart");
        }
        JsonModel jm = new JsonModel();
        jm.setCode(1);
        jm.setObj(cart.values());
        super.writeJson(jm,resp);
    }
    //删除购物
    protected void remove(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, InstantiationException, IllegalAccessException {
        int sid = Integer.parseInt(req.getParameter("sid"));
        HttpSession session = req.getSession();//取出session会话对象

        Map<Integer, CartItem> cart = new HashMap<Integer,CartItem>();//购物车  集合
        if (session.getAttribute("cart")!=null){
            cart = (Map<Integer, CartItem>) session.getAttribute("cart");
        }
        if (cart.containsKey(sid)){
            //判断  用户是否购买了这个商品
            //如果有  则数量++
            cart.remove(sid);
        }
        //4.存入session
        session.setAttribute("cart",cart);
        //5.返回jsonModel(code=1，obj=cart.values(所有的CartItem集合))
        JsonModel jm = new JsonModel();
        jm.setCode(1);
        jm.setObj(cart.values());
        super.writeJson(jm,resp);
    }
    //显示已下单的商品状态
    protected void findShoesStatus(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        HttpSession session = req.getSession();//取出session会话对象
        User user = (User) session.getAttribute(USER);
        String userid = String.valueOf(user.getUserid());
        System.out.println(userid);
        JsonModel jm = new JsonModel();
        String sql = "select ShoeOrder.oid,photourl,sdescription,dealprice,num,paymentstatus,orderstatus\n" +
                "from Shoes JOIN ShoePhotos ON Shoes.sid = ShoePhotos.sid,ShoeOrder,resorderitem,user\n" +
                "where resorderitem.oid=ShoeOrder.oid and resorderitem.sid=Shoes.sid and ShoeOrder.userid=User.userid\n" +
                "    and ismain='true' and user.userid=?";
        List<ShoeStatus> list = db.select(ShoeStatus.class,sql,userid);

        Map<Integer, List<ShoeStatus>> groupedByOid = list.stream()
                .collect(Collectors.groupingBy(ShoeStatus::getOid));

        // 将分组结果存储到 List<List<ShoeStatus>> 中
        List<List<ShoeStatus>> result = new ArrayList<>(groupedByOid.values());


        jm.setCode(1);
        jm.setObj(result);
        super.writeJson(jm,resp);
    }
    //签收
    protected void sign(HttpServletRequest req, HttpServletResponse resp) throws Exception {
        JsonModel jm = new JsonModel();
        int oid = Integer.parseInt(req.getParameter("oid"));

        String findPayStatus_sql = "select ShoeOrder.oid,photourl,sdescription,dealprice,num,paymentstatus,orderstatus\n" +
                "from Shoes JOIN ShoePhotos ON Shoes.sid = ShoePhotos.sid,ShoeOrder,resorderitem\n" +
                "where resorderitem.oid=ShoeOrder.oid and resorderitem.sid=Shoes.sid\n" +
                "  and ShoeOrder.oid=?";
        List<ShoeStatus> list = db.select(ShoeStatus.class,findPayStatus_sql,oid);
        ShoeStatus s = list.get(0);
        if (!s.getPaymentstatus().equals("已支付")){
            jm.setCode(0);
            jm.setError("未支付，请先支付！！！！");
            return;
        }else {
            String sql = "update ShoeOrder set orderstatus = '已签收' where oid=? ";
            int result = db.doUpdate(sql,oid);
            if (result==1){
                jm.setCode(1);
            }else {
                jm.setCode(0);
            }
        }
        super.writeJson(jm,resp);
    }
}
